#pragma once
#include<iostream>
#include"connection.hpp"
//#include "epoller.hpp"

class Reactor;
class Channel{
    public:
        Channel(int fd):_fd(fd){
            _connection=nullptr;
        }
        ~Channel(){}
        void SetConnection(Connection* conn){
            _connection=conn;
        }
        void SetReactor(Reactor* reactor){
            _reactor=reactor;
        }
        void BuildChannle(){

        }
        virtual bool Send(){
            if(_connection==nullptr){
                LOG(ly::LogLevel::ERROR)<<"未连接"<<"\n";
                return false;
            }
            _protocol.Serialize(_outbuffer);
            int n=send(_fd,_outbuffer.c_str(),_outbuffer.size(),0);
            if(n<0){
                LOG(ly::LogLevel::ERROR)<<"发送失败"<<"\n";
                return false;
            }
            else{
                _outbuffer.clear();
            }
            return true;
        }
        virtual int Recv(){
            if(_connection==nullptr){
                LOG(ly::LogLevel::ERROR)<<"未连接"<<"\n";
                return false;
            }
            int n=_connection->Recv(_inbuffer);
            if(n<0){
                return n;
            }
            else if(n==0){
                return n;
            }
            LOG(ly::LogLevel::INFO)<<_inbuffer<<"\n";
            // std::string sz;
            // while(true){
            //     sz=_protocol.Deserialization(_inbuffer);//反序列化函数会改变_inbuffer的内容
            //     if(sz=="||"){
            //         break;
            //     }
            //     else{
            //         LOG(ly::LogLevel::INFO)<<sz<<"\n";
            //         //处理消息
            //     }
            // }
            return true;
        }
    private:
        int _fd;
        std::string _inbuffer, _outbuffer;
        Connection* _connection;
        TcpProtocol _protocol;
        Reactor* _reactor;
};
